<template>
  <div>
    <button @click="useAbility">使用技能</button>
    <button @click="nighrInfo">昨夜信息</button>
    <button @click="toVote">进行投票</button>
    <button @click="checkRole">查看身份</button>
    <template v-if="creator === user">
      <button @click="startGame">开始游戏</button>
    </template>
    <template v-if="creator === user">
      <button @click="reissue">重新发牌</button>
    </template>
  </div>
  <div>
    <h2>玩家列表</h2>
    <ul>
      <li v-for="(item, index) in playerList" :key="index">{{ index }}. {{ item }}</li>
    </ul>
  </div>
  <div>
    <button @click="refresh">刷新</button>
  </div>
  <template v-if="isuseAbility === true">
    <div class="popup">
      <h2>{{ chooseTitle }}</h2>
      <h3>{{ small_title }}</h3>
      <div>
        <button v-for="(item, index) in board" :key="index" @click="choosing(index)">{{ index }}. {{ item }}</button>
      </div>
    </div>
  </template>
</template>




<script setup>
  import { ref, onMounted, getCurrentInstance, watch } from 'vue'
  import { useRouter } from 'vue-router'
  import axios from 'axios'

  onMounted(() => {
    RoomInfo();
  })

  const instance = getCurrentInstance();
  const router = useRouter()

  const room = instance.proxy.$route.params.room;
  const user = instance.proxy.$route.params.user;
  const role = ref('');
  const currentRoleList = ref([]);
  const preRole = ref('');
  const player = ref(0);
  const playerList = ref([]);
  const selfNo = ref('');
  const creator = ref('');
  const isuseAbility = ref(false);
  const board = ref([]);

  const RoomInfo = () => {
    try {
      axios.get(`http://localhost:5353/room`, { params: { room: room, user: user } })
        .then(res => {
          role.value = res.data.selfRole;
          currentRoleList.value = res.data.roleList;
          playerList.value = res.data.playerList;
          selfNo.value = res.data.No;
          creator.value = res.data.creator;
          player.value = res.data.playerNo;
          GetPreviousRole(currentRoleList.value[role.value - 1]);

          if (role.value == -1) {
            alert("房间已满！");
            window.history.back();
          }
          if (role.value == -2) {
            alert("该房间不存在！");
            window.history.back();
          }

        })
    }
    catch (err) {
      console.log(err);
    }
  }

  const checkRole = () => {
    alert("你的身份是：" + RoleSearch(currentRoleList.value[role.value - 1]));
  }

  const reissue = () => {
    try {
      axios.get(`http://localhost:5353/reissue?room=${room}&playerNo=${player.value}`)
        .then(res => {
          console.log("重新发牌成功！");
          refresh();
        })
    }
    catch (err) {
      console.log(err);
    }
  }

  const refresh = () => {
    window.location.reload();
  }

  const nighrInfo = () => {
    try {
      axios.get(`http://localhost:5353/play`, { params: { acquire3: true, item: "death1", item2: "death2", item3: "death3", room: room } })
        .then(res => {
          console.log("夜晚信息获取成功！");
          var deadInfo = "";
          var d = res.data.split(" ");
          for (let i = 0; i < d.length; i++) {
            if (parseInt(d[i]) != 0) {
              deadInfo += d[i] + "号"
            }
          }
          if (deadInfo != "") {
            alert("昨晚被袭击的是: " + deadInfo);
          }
          else {
            alert("昨晚是平安夜！");
          }
        })
    }
    catch (err) {
      console.log(err);
    }
  }

  const useAbility = () => {
    GetCurrentOrder(currentRoleList.value[role.value - 1], function (data, status) {
      let rm = parseInt(data);
      if (rm > 0) {
        isuseAbility.value = true;
        PrepareChooseBoard(currentRoleList.value[role.value - 1]);
      }
    })
  }

  const startGame = () => {
    try {
      axios.get(`http://localhost:5353/play`, { params: { room: room, start: true } })
        .then(res => {
          if (res.data.trim() == "success") {
            setTimeout(function () { new Audio('http://localhost:5353/voice/start.mp3').play(); }, 1000);
            setTimeout(function () { new Audio('http://localhost:5353/voice/wolf1.mp3').play(); }, 5000);
            setTimeout(function () { new Audio('http://localhost:5353/voice/wolf2.mp3').play(); }, 8000);
          }
        })
    }
    catch (err) {
      console.log(err);
    }

    var funcitonRole = [];
    var intervalId = [];
    for (let index = 0; index < roleOrder.length; index++) {
      if (currentRoleList.value.indexOf(roleOrder[index]) != -1) {
        funcitonRole.push(roleOrder[index]);
        intervalId.push(0);
      }
    }
    for (let index = 0; index < funcitonRole.length; index++) {
      intervalId[index] = setInterval(function () {
        axios.get(`http://localhost:5353/play`, { params: { role: funcitonRole[index], verify: true, room: room } })
          .then(res => {
            let rm = parseInt(res.data);
            if (rm > 0) {
              new Audio('http://localhost:5353/voice/' + funcitonRole[index] + 'e.mp3').play();
              if (index < funcitonRole.length - 1)
                setTimeout(function () { new Audio('http://localhost:5353/voice/' + funcitonRole[index + 1] + 's.mp3').play(); }, 5000);
              else
                {
                  setTimeout(function () { new Audio('http://localhost:5353/voice/sunrise.mp3').play(); }, 5000);
                  try{
                    axios.get(`http://localhost:5353/judge`, { params: { room: room, role: funcitonRole[index] } });
                  }
                  catch (err){
                    console.log(err);
                  }
                }
              clearInterval(intervalId[index]);
            }
          })
      }, 5000);
    }
  }

  const RoleSearch = (dashMark) => {
    return roleList[dashMark];
  }

  const roleList = {
    "g-seer": "预言家",
    "g-witch": "女巫",
    "g-hunter": "猎人",
    "g-idiot": "白痴",
    "g-knight": "骑士",
    "g-guard": "守卫",
    "g-dreamtaker": "摄梦人",
    "g-magician": "魔术师",
    "w-white": "白狼王",
    "w-hidden": "隐狼",
    "w-king": "狼王",
    "w-devil": "恶魔",
    "w-beauty": "狼美人",
    "w-knight": "恶灵骑士",
    "w": "狼人",
    "f": "平民"
  }

  const roleOrder = ['g-magician', 'w', 'w-devil', 'w-beauty', 'g-witch', 'g-guard', 'g-seer', 'g-dreamtaker']

  const chooseTitle = ref("")
  const small_title = ref("")
  const already_choose = ref(false)
  const choose_who = ref("")


  const PrepareChooseBoard = (selfRole) => {
    if (selfRole == "w-devil") {
      chooseTitle.value = "恶魔";
      small_title.value = "请选择你要查验的对象：";
      already_choose.value = false;
      board.value = playerList.value;
      watch(already_choose, (oldVal, newVal) => {
        try {
          axios.get(`http://localhost:5353/view`, { params: { role: "w-devil", board: choose_who.value, room: room } })
            .then(res => {
              var goodGuy = "平民"
              if (currentRoleList.value[res.data - 1][0] == "g") {
                goodGuy = "神职"
              }
              alert("他是 " + goodGuy)
              try {
                axios.get(`http://localhost:5353/operation`, { params: { "b-info": "w-devil", "b-prev": preRole.value, "b-room": room, "b-self": user, board: choose_who.value } })
              } catch (err) {
                console.log(err);
              }
            })
        } catch (err) {
          console.log(err);
        }
      })
    }
    else if (selfRole[0] == "w") {
      chooseTitle.value = "狼人";
      small_title.value = "请选择你要袭击的对象：";
      already_choose.value = false;
      board.value = playerList.value;
      watch(already_choose, (oldVal, newVal) => {
        try {
          axios.get(`http://localhost:5353/operation`, { params: { "b-info": "w", "b-prev": preRole.value, "b-room": room, "b-self": user, board: "board-" + choose_who.value } })
        } catch (err) {
          console.log(err);
        }
      })
    }
    else if (selfRole == "g-witch") {
      chooseTitle.value = "女巫";
      try {
        axios.get(`http://localhost:5353/play`, { params: { acquire3: true, item: "death1", item2: "g-witch", item3: "death2", room: room } })
          .then(res => {
            let d = res.data.split(" ");
            if (Math.abs(d[1])% 4 == 1 || Math.abs(d[1]) % 4 == 3) {
              alert("你已使用过解药！")
            }
            else {
              if (d[0] != 0) {
                small_title.value = "昨晚被袭击的是：" + d[0] + "号。是否使用解药？";
                already_choose.value = false;
                board.value = ['是', '否'];
                var witch_save = false;
                var witch_poison = false;
                watch(already_choose, (oldVal, newVal) => {
                  if (!witch_save) {
                    witch_save = true;
                    if (choose_who.value == 0) {
                      try {
                        axios.get(`http://localhost:5353/operation`, { params: { "b-info": "g-witch", "b-prev": preRole.value, "b-room": room, "b-self": user, "flip-checkbox": "on" } })
                        stopwatch();
                      }
                      catch (err) {
                        console.log(err);
                      }
                    }
                    else {
                      isuseAbility.value = true;
                      small_title.value = "是否使用毒药？";
                      board.value = ['是', '否'];
                      alert(witch_poison)
                    }
                  }
                  else {
                    if (!witch_poison) {
                      witch_poison = true;
                      if (choose_who.value == 0) {
                        if (Math.abs(d[1]) % 4 == 2 || Math.abs(d[1]) % 4 == 3) {
                          alert("你已使用过毒药！");
                          stopwatch();
                        }
                        else {
                          isuseAbility.value = true;
                          small_title.value = "请选择你要毒害的对象：";
                          board.value = playerList.value;
                        }
                      }
                      else
                        stopwatch();
                    }
                    else {
                      try {
                        axios.get(`http://localhost:5353/operation`, { params: { "b-info": "g-witch", "b-prev": preRole.value, "b-room": room, "b-self": user, board: "board-" + choose_who.value } })
                        stopwatch();
                      }
                      catch (err) {
                        console.log(err);
                      }
                    }
                  }
                })
              }
            }
          })
      }
      catch (err) {
        console.log(err);
      }
    }
    else if (selfRole == "g-seer") {
      chooseTitle.value = "预言家";
      small_title.value = "请选择你要查验的对象：";
      already_choose.value = false;
      board.value = playerList.value;
      watch(already_choose, (oldVal, newVal) => {
        try {
          axios.get(`http://localhost:5353/view`, { params: { role: "g-seer", board: choose_who.value, room: room } })
            .then(res => {
              var goodGuy = "好人";
              if (currentRoleList.value[res.data - 1][0] == "w" && currentRoleList.value[res.data - 1] != "w-hidden") {
                goodGuy = "狼人"
              }
              alert("他是 " + goodGuy);
              try {
                axios.get(`http://localhost:5353/operation`, { params: { "b-info": "g-seer", "b-prev": preRole.value, "b-room": room, "b-self": user, board: choose_who.value } })
              } catch (err) {
                console.log(err);
              }
            })
        } catch (err) {
          console.log(err);
        }
      })
    }
    else if (selfRole == "g-guard") {
      chooseTitle.value = "守卫";
      small_title.value = "请选择你要守卫的对象：";
      already_choose.value = false;
      board.value = playerList.value;
      watch(already_choose, (oldVal, newVal) => {
        try {
          axios.get(`http://localhost:5353/operation`, { params: { "b-info": "g-guard", "b-prev": preRole.value, "b-room": room, "b-self": user, board: "board-" + choose_who.value } })
        } catch (err) {
          console.log(err);
        }
      })
    }
  }

  const CheckPredecessorStatus = (preRole, callback) => {
    try {
      axios.get(`http://localhost:5353/play`, { params: { role: preRole, verify: true, room: room } })
        .then(res => { callback(res.data, 200) })
    }
    catch (err) {
      console.log(err);
    }
  }

  const GetPreviousRole = (selfRole) => {
    let m = roleOrder.indexOf(selfRole);
    if (m == -1 || m == 0) {
      preRole.value = "start";
    }
    else {
      let i = m - 1;
      for (; i >= 0; i--) {
        if (currentRoleList.value.indexOf(roleOrder[i]) != -1) {
          preRole.value = roleOrder[i];
          break;
        }
      }
      if (i == -1) {
        preRole.value = "start";
      }
    }
  }

  const GetCurrentOrder = (selfRole, callback) => {
    GetPreviousRole(selfRole);
    CheckPredecessorStatus(preRole.value, callback)
  }

  const choosing = (item) => {
    already_choose.value = -already_choose.value;
    choose_who.value = item;
    isuseAbility.value = false;
  }

</script>
